//
//  GYAliyunOSS.m
//  GeYou
//
//  Created by keven kenv on 2017/12/20.
//  Copyright © 2017年 geyou. All rights reserved.
//

#import "GYAliyunOSS.h"
#import <AliyunOSSiOS/OSSService.h>
#import "Head.h"
//http://cosmolove.image.alimmdn.com/img/photo/
//res2.geyoumall.com  oss-cn-beijing.aliyuncs.com
NSString * const endPoint = @"https://oss-cn-beijing.aliyuncs.com";
NSString * const multipartUploadKey = @"multipartUploadObject";
//NSString * const httpurl = @"http://192.168.4.112:8082/webservice/secure/getOssToken.html";
NSString * const httpurl = @"http://101.201.171.131:8080/rest/api/photo/ossToken";
OSSClient *client;
static dispatch_queue_t queue4demo;

@implementation GYAliyunOSS
-(void)uploadObjectAsync
{
    
}
+ (instancetype)sharedInstance {
    static GYAliyunOSS *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [GYAliyunOSS new];
    });
    return instance;
}

- (void)setupEnvironment {
    // 打开调试log
    [OSSLog enableLog];
    
    // 初始化sdk
    [self initOSSClient];
}

- (void)initOSSClient {
    id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
        NSURL * url = [NSURL URLWithString:httpurl];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

        NSMutableDictionary* para=[NSMutableDictionary new];
        [para setObject:@"1" forKey:@"deviceType"];
        [para setObject:@"1" forKey:@"type"];
        [request setHTTPBody:[para yy_modelToJSONData]];
        [request setHTTPMethod:@"POST"];
        
        OSSTaskCompletionSource * tcs = [OSSTaskCompletionSource taskCompletionSource];
        NSURLSession * session = [NSURLSession sharedSession];
        NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request
                                                    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                        if (error) {
                                                            [tcs setError:error];
                                                            return;
                                                        }
                                                        [tcs setResult:data];
                                                    }];
        [sessionTask resume];
        [tcs.task waitUntilFinished];
        if (tcs.task.error) {
            NSLog(@"get token error: %@", tcs.task.error);
            return nil;
        } else {
            NSDictionary * object = [NSJSONSerialization JSONObjectWithData:tcs.task.result
                                                                    options:kNilOptions
                                                                      error:nil];
            OSSFederationToken * token = [OSSFederationToken new];
            token.tAccessKey = [object objectForKey:@"accessKeyId"];
            token.tSecretKey = [object objectForKey:@"accessKeySecret"];
            token.tToken = [object objectForKey:@"securityToken"];
            token.expirationTimeInGMTFormat = [object objectForKey:@"expiration"];
            NSLog(@"get token: %@", token);
            return token;
        }
    }];
    
    
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    conf.maxRetryCount = 2;
    conf.timeoutIntervalForRequest = 30;
    conf.timeoutIntervalForResource = 24 * 60 * 60;
    
    client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential clientConfiguration:conf];
    
}

//同步上传
- (void)uploadObjectSyncWithImageUrl:(NSURL *)url dir:(NSString *)dir completion:(void(^)(NSDictionary *error, NSString *imgName))completion {
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    NSDate *senddate = [NSDate date];
    NSString *date2 = [NSString stringWithFormat:@"%ld", (long)[senddate timeIntervalSince1970]];
    // required fields
    put.bucketName = kBucketName;
    
    NSString *imgName = [NSString stringWithFormat:@"%@/%@gyios", dir, date2];
    put.objectKey = imgName;
    
    
    put.uploadingFileURL = url;
    
    // optional fields
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    put.contentType = @"";
    put.contentMd5 = @"";
    put.contentEncoding = @"";
    put.contentDisposition = @"";
    
    OSSTask * putTask = [client putObject:put];
    
//    [putTask waitUntilFinished]; // 阻塞直到上传完成
    [putTask continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
        if (!putTask.error) {
            NSLog(@"upload object success!");
            NSString *imgPath = [NSString stringWithFormat:@"http://%@/%@", kAliUrl, imgName];
            if (completion) {
                completion(nil, imgPath);
            }
        } else {
            NSLog(@"upload object failed, error: %@" , putTask.error);
            NSString *errorcode = [NSString stringWithFormat:@"%ld",putTask.error.code];
            NSString *domain = putTask.error.domain;
            NSDictionary *dic = @{@"errorCode":errorcode,@"errorMessage":domain};
            if (completion) {
                completion(dic, nil);
            }
        }
        return nil;
    }];
}





-(void)uploadImages:(NSArray *)images isAsync:(BOOL)isAsync complete:(void (^)(NSArray *, NSString *))complete
{

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = images.count;
    
    NSMutableArray *callBackNames = [NSMutableArray array];
    int i = 0;
    for (UIImage *image in images) {
        if (image) {
            NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
                
                
                NSDate *senddate = [NSDate date];
                NSString *date2 = [NSString stringWithFormat:@"%ld%d", (long)[senddate timeIntervalSince1970],i];
                NSString *imageName = [NSString stringWithFormat:@"%@/%@gyios", kProduct, date2];
                
                //任务执行
                OSSPutObjectRequest * put = [OSSPutObjectRequest new];
                put.bucketName = kBucketName;
            
                put.objectKey = imageName;
            
                NSData *data = UIImageJPEGRepresentation(image, 0.6);
                put.uploadingData = data;
                
                OSSTask * putTask = [client putObject:put];
                [putTask waitUntilFinished]; // 阻塞直到上传完成
                if (!putTask.error) {
                    NSLog(@"upload object success!");
                    NSString *imgPath = [NSString stringWithFormat:@"http://%@/%@", kAliUrl, imageName];
                    [callBackNames addObject:imgPath];
                } else {
                    NSLog(@"upload object failed, error: %@" , putTask.error);
                }
                if (isAsync) {
                    if (image == images.lastObject) {
                        NSLog(@"upload object finished!");
                        if (complete) {
                            complete([NSArray arrayWithArray:callBackNames] ,@"1");
                        }
                    }
                }
            }];
            if (queue.operations.count != 0) {
                [operation addDependency:queue.operations.lastObject];
            }
            [queue addOperation:operation];
        }
        i++;
    }
    if (!isAsync) {
        [queue waitUntilAllOperationsAreFinished];
        NSLog(@"haha");
        if (complete) {
            if (complete) {
                complete([NSArray arrayWithArray:callBackNames], @"1");
            }
        }
    }
}
@end



